import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { Button, Tree, Pagination, message } from 'antd';
import { FolderAddOutlined, FolderOutlined } from '@ant-design/icons';
import type { ImagesListItem, ImagesListParams } from './data';
import styles from './index.less';

import RightHeader from './components/RightHeader';
import SortableImages from './components/SortableImages';
import { queryImages, queryFiles, addFile } from './service';

// 新增文件夹操作
const handleAddFile = async (params: ImagesListParams) => {
  const hide = message.loading('正在添加');
  try {
    await addFile({ ...params });
    hide();
    message.success('添加成功');
    return true;
  } catch (err) {
    hide();
    message.error('添加失败请重试');
    return false;
  }
};

const OnlineImage: React.FC = () => {
  // 记录当前被选中的文件节点id，默认100
  const [selectedFileKey, setSelectedFileKey] = useState('100');
  // 记录模拟文件夹数据，初始化数据
  const [filesMockList, setFilesMockList] = useState<ImagesListItem[]>([]);
  // 记录模拟图片数据，初始化数据
  const [imagesMockList, setImagesMockList] = useState<ImagesListItem[]>([]);
  // 记录搜索数据
  const [searchTitle, setSearchTitle] = useState('');
  // 记录分页数据
  const [paginationData, setPaginationData] = useState({
    defaultCurrent: 1,
    pageSize: 10,
    total: 0,
  });
  // 新增文件夹弹窗
  const [addModalVisible, setAddModalVisible] = useState(false);

  const getFiles = async () => {
    try {
      const { data } = await queryFiles();

      setFilesMockList(() => {
        data.map((item) => {
          item.icon = <FolderOutlined />;
        });
        filesMockList.length = 0;
        filesMockList.push(...data);
        return [...filesMockList];
      });
    } catch (err) {
      console.log(err);
    }
  };

  const getImages = async (params?: ImagesListParams) => {
    try {
      const { data, current, pageSize, total } = await queryImages({ ...params });
      // 更新imagesMockList
      setImagesMockList(() => {
        // 对图片名称进行简略显示
        data.forEach((item: ImagesListItem) => {
          if (item.name.length > 8) {
            item.title = item.name.substring(0, 8) + '...';
          }
        });
        imagesMockList.length = 0;
        imagesMockList.push(...data);
        return [...imagesMockList];
      });

      // 更新filesMockList的children
      setFilesMockList(() => {
        filesMockList.forEach((fileItem: ImagesListItem) => {
          const children: ImagesListItem[] = [];
          data.forEach((imageItem: ImagesListItem) => {
            if (imageItem.parentId === fileItem.id) {
              children.push(imageItem);
            }
          });
          fileItem.title =
            fileItem.name.length > 8 ? fileItem.name.substring(0, 8) + '...' : fileItem.name;
          fileItem.children!.length = 0;
          fileItem.children!.push(...children);
        });

        return [...filesMockList];
      });

      setPaginationData({
        defaultCurrent: current,
        pageSize,
        total: total,
      });
    } catch (err) {
      console.log({ err });
    }
  };

  useEffect(() => {
    new Promise<void>((resolve, reject) => {
      getFiles()
        .then(() => {
          // 初始化时，默认传入第一个文件夹id
          getImages({ parentId: filesMockList[0]?.id } || '');
          resolve();
        })
        .catch((err) => {
          console.log(err);
          reject(err);
        });
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <PageContainer>
      <ProCard split="vertical">
        <ProCard
          colSpan="20%"
          title={
            <Button type="primary" ghost onClick={() => setAddModalVisible(true)}>
              <FolderAddOutlined />
              新建文件夹
            </Button>
          }
        >
          <Tree
            showIcon
            loadData={({ key }) => getImages({ parentId: key as string })}
            treeData={filesMockList}
            onSelect={(_, { node: { key, isLeaf } }) => {
              if (!isLeaf) {
                setSelectedFileKey(key as string);
                getImages({ parentId: key as string });
              }
            }}
          />
        </ProCard>
        <ProCard
          className={styles['pro-card']}
          title={
            <RightHeader
              getImages={getImages}
              setSearchTitle={setSearchTitle}
              selectedFileItem={
                filesMockList.find((item) => item.key === selectedFileKey) as ImagesListItem
              }
            />
          }
          headerBordered
        >
          <div className={styles['right-content']}>
            <SortableImages
              imagesList={imagesMockList}
              setImagesList={setImagesMockList}
              getImages={getImages}
              searchTitle={searchTitle}
              paginationData={paginationData}
            />
          </div>
          {imagesMockList.length > 0 ? (
            <div className={styles['right-footer']}>
              <Pagination
                {...paginationData}
                showQuickJumper
                showSizeChanger
                showTotal={(total) => `共有${total}张图片`}
                onChange={(page: number, pageSize: number) =>
                  getImages({
                    currentPage: page,
                    pageSize,
                    parentId: imagesMockList[0]?.parentId || '',
                    title: searchTitle,
                  })
                }
              />
            </div>
          ) : (
            ''
          )}
        </ProCard>
      </ProCard>

      <ModalForm
        title="新建文件夹"
        width="300px"
        visible={addModalVisible}
        onVisibleChange={setAddModalVisible}
        onFinish={async (params: ImagesListParams) => {
          // 确认提交操作
          const success = await handleAddFile({ ...params });
          if (success) {
            getFiles();
            setAddModalVisible(false);
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '文件名不可以为空',
            },
          ]}
          width="sm"
          name="title"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default OnlineImage;
